#pragma once

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include "Common.hpp"

class InetAddr
{
public:
    InetAddr()
    {
    }
    InetAddr(const struct sockaddr_in &addr) : _net_addr(addr)
    {
        PortN2H();
        IpN2H();
    }
    InetAddr(uint16_t port) : _port(port), _ip("")
    {
        _net_addr.sin_family = AF_INET;
        _net_addr.sin_port = ::htons(port);
        _net_addr.sin_addr.s_addr = INADDR_ANY;
    }
    bool operator==(const InetAddr &addr)
    {
        return _ip == addr._ip && _port == addr._port;
    }
    struct sockaddr *NetAddr() { return CONV(&_net_addr); }
    socklen_t NetAddrLen() { return sizeof(_net_addr); }
    std::string Ip() { return _ip; }
    uint16_t Port() { return _port; }
    std::string Addr() { return Ip() + ":" + std::to_string(_port); }
    void SetAddr(const sockaddr_in &client, socklen_t &len)
    {
        _net_addr = client;
        IpN2H();
    }

private:
    void PortN2H()
    {
        _port = ::ntohs(_port);
    }
    void IpN2H()
    {
        char buffer[64];
        _ip = ::inet_ntop(AF_INET, &_net_addr.sin_addr, buffer, sizeof(buffer));
    }

    struct sockaddr_in _net_addr;
    std::string _ip;
    uint16_t _port;
};